<script setup>
import {inject, onMounted, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const $http = inject("$axios");

const tableData = ref([]);

onMounted(() => {
  $http.get("http://localhost:8088/api/user/findAll").then(res => {
    tableData.value = res.data;
  });
});

function changeInfo() {
  router.push('/update');
}

function deleteInfo(row) {
  // 确保传递的是整行数据，以便获取id
  const id = row.userId; // 从传入的行数据中提取id

  $http.delete(`http://localhost:8088/api/user/deleteUser/${id}`)
      .then(() => {
        // 使用filter方法从tableData中移除对应的用户数据
        tableData.value = tableData.value.filter(item => item.userId !== id);
        // 显示删除成功的消息
        ElMessage.success('删除成功！');
      })
      .catch(error => {
        // 打印错误信息到控制台，并显示错误消息
        console.error('删除失败：', error);
        ElMessage.error('删除失败：' + error.message);
      });
}
</script>

<template>
  <div class="function">
    <h1>用户管理</h1>
    <el-table
        :data="tableData"
        border
        style="width: 100%;">     <!-- 列表宽度占页面100%-->
      <!-- 设置列表中的各列-->
      <el-table-column
          fixed
          prop="userId"
          label="用户名">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名">
      </el-table-column>
      <el-table-column
          prop="password"
          label="密码">
      </el-table-column>
      <el-table-column
          prop="sex"
          label="性别">
      </el-table-column>
      <el-table-column
          prop="age"
          label="年龄">
      </el-table-column>
      <el-table-column
          prop="phone"
          label="电话">
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱">
      </el-table-column>
      <el-table-column
          prop="job"
          label="职务">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作">
        <template v-slot="scope">
          <el-button type="text" size="small" @click="changeInfo(scope.row)">编辑</el-button>           <!--编辑功能按钮-->
          <el-button @click="deleteInfo(scope.row)" type="text" size="small">删除</el-button>  <!--删除功能按钮-->
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>

</style>